import uuid
from django.db import models

class PrefixedUUIDField(models.CharField):
    def __init__(self, prefix='', *args, **kwargs):
        self.prefix = prefix
        kwargs['max_length'] = len(prefix) + 36  # 36 是标准 UUID 的长度
        super().__init__(*args, **kwargs)

    def pre_save(self, model_instance, add):
        if add and not getattr(model_instance, self.attname):
            unique_id = str(uuid.uuid4())
            value = f"{self.prefix}{unique_id}"
            setattr(model_instance, self.attname, value)
            return value
        else:
            return super().pre_save(model_instance, add)

class Questionnaire(models.Model):
    id = PrefixedUUIDField(primary_key=True, prefix='QN_', editable=False)
    title = models.CharField(max_length=100)
    qtype = models.IntegerField(default=0) # 问卷类型: 0: 普通问卷, 1: 检测报告卷
    description = models.TextField()
    creator = models.ForeignKey('auth.User', on_delete=models.PROTECT)
    status = models.IntegerField(default=0) # 0: 未发布, 1: 已发布, 2: 已结束 3: 已删除
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    version = models.IntegerField(default=1)  # 新增版本号字段

class Question(models.Model):
    id = PrefixedUUIDField(primary_key=True, prefix='Q_', editable=False)
    questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='questions')
    qnum = models.IntegerField(default=0) # 问题序号
    title = models.TextField()
    qtype = models.CharField(default='radio', max_length=12) # 问题类型: raido/checkbox/text
    options = models.JSONField(blank=True, null=True)
    module = models.CharField(default='', max_length=12) # 问题模块: 可能分模块或分页时用
    status = models.IntegerField(default=0) # 0: normal, 1: deleted 
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.text

class Answer(models.Model):
    id = PrefixedUUIDField(primary_key=True, prefix='ANS_', editable=False)
    questionnaire = models.ForeignKey(Questionnaire, on_delete=models.PROTECT, related_name='answers')
    questionnaire_version = models.IntegerField()  # 关联问卷版本号
    user = models.ForeignKey('auth.User', on_delete=models.PROTECT)
    answers = models.JSONField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f'Answers For {self.questionnaire.title} by {self.user.username}'